<template lang="pug">
  .clearfix
    Modal(
      width="400"
      v-model="isShowBatchModifyModal"
      title="批量修改花名册"
      class-name="vertical-center-modal"
    )
      Form.clearfix(ref="formData" :model="formData" :rules="setRules" :label-width="100")
        FormItem.form-item(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'radio'")
            RadioGroup(v-model="formData[item.model]"  @on-change="radioChange($event)")
              Radio.display-inline-block(v-for="(c_item, index) of arrListDown[item.options]" :label="c_item.value" :key="index") {{c_item.label}}
          template(v-if="item.type === 'select'")
            Select.w180(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
              Option(
                v-for="(c_item, index) in arrListDown[item.options]"
                :value="c_item.value"
                :key="index"
              ) {{ c_item.label }}
      Row
        Col.pl-10(span="24")
          Button.pull-left.mr-10(:to="setTemplateDownLoadUrl" target="_blank") 模板下载
          Upload(
            ref="upload"
            :before-upload="handleBeforeUploadBatchModify"
            :on-success="uploadSuccessBatchModify"
            accept=".xls, .xlsx"
            :max-size="10 * 1024"
            :on-exceeded-size="handleMaxSizeTen"
            :action="actionUrl"
            :headers="headers"
            :show-upload-list="false"
            :data="{...formData, companyGUID: companyId}"
          )
            Button(type="info") 导入
        Col.pl-10(span="24")
          .text-gray-9.pt-10.pb-10 仅支持上传10M以内的xlsx文件
        Col.pl-10.pt-10(span="24")
          Tag(v-if="file") {{file.name}}
        Col.pl-10.pt-10(span="24" v-if="errorData.isError")
          Button(type="warning" :to="errorData.downLoadUrl" target="_blank") 下载错误文件

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmitBatchModify" :loading="!isCanSubmit") 确定
</template>

<script>
import { Common } from '@/utils/common.js'
import Cookies from 'js-cookie'
import { EmployeesApi } from '@/api/Employees.api.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  props: {
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      isShowBatchModifyModal: false,
      companyId: null,
      companyName: null,
      file: null,
      errorData: {
        errorId: '',
        isError: false,
        downLoadUrl: null
      },
      // templateDownLoadUrl: baseUrl + 'Content/Template/员工花名册批量修改模板.xlsx?random=' + Math.floor(Math.random() * 10),
      isCanSubmit: true,
      // actionUrl: ''
      formData: {
        importType: 0,
        fieldName: null,
      },
      formItem: [
        { type: 'radio', label: '导入方式：', placeholder: '请选择导入方式', prop: 'importType', model: 'importType', style: 'ivu-col-span-24', options: 'importTypeOps' },
        { type: 'select', label: '修改字段：', placeholder: '请选择修改字段', prop: 'fieldName', model: 'fieldName', style: 'ivu-col-span-24', options: 'fieldNameOps' },
      ],
      rules: {
        fieldName: [
          { required: true, message: '请选择修改字段', trigger: 'change' }
        ],
      },
      arrListDown: {
        importTypeOps: [{label: '多字段修改', value: 0}, {label: '单字段修改', value: 1}],
        fieldNameOps: []
      },
    }
  },

  watch: {
  },

  computed: {
    actionUrl () {
      return this.companyId && this.companyName ? baseUrl + 'api/Employee/BatchUpdateEmployees?CompanyGUID=' + this.companyId : baseUrl + 'api/Employee/BatchUpdateEmployeesAll'
    },

    setTemplateDownLoadUrl () {
      if (this.formData.importType == 0) {
        return this.companyId && this.companyName ? baseUrl + 'Content/Template/员工花名册批量修改模板.xlsx?random=' + Math.floor(Math.random() * 10) : baseUrl + 'Content/Template/员工管理批量修改模板.xlsx?random=' + Math.floor(Math.random() * 10)
      } else {
        return this.companyId && this.companyName ? baseUrl + 'Content/Template/员工花名册批量修改模板单字段.xlsx?random=' + Math.floor(Math.random() * 10) : baseUrl + 'Content/Template/员工管理批量修改模板单字段.xlsx?random=' + Math.floor(Math.random() * 10)
      }
    },

    setRules () {
      if (this.formData.importType == 0) {
        // console.log('多字段修改')
        this.rules.fieldName = [{ required: true, message: '请选择修改字段', trigger: 'change' }]
      } else if (this.formData.importType == 1) {
        // console.log('单字段修改')
        this.rules.fieldName = []
      }
      return this.rules
    },

    setFormItem () {
      if (this.formData.importType == 1) {
        this.formItem[1].style = 'ivu-col-span-24'
      } else {
        this.formItem[1].style = 'ivu-col-span-24 display-none'
      }
      return this.formItem
    }
  },

  mounted () {
    this.getFiledList()
    // this.companyId = this.$route.query.companyId
    // this.companyName = this.$route.query.companyName
  },

  methods: {
    cancel () {
      this.isShowBatchModifyModal = false
      this.file = null
    },

    show (companyId, companyName) {
      this.formData.importType = 0
      this.formData.fieldName = null
      this.companyId = companyId
      this.companyName = companyName
      this.isCanSubmit = true
      this.isShowBatchModifyModal = true
      this.file = null
    },

    // 获取修改字段下拉框
    async getFiledList () {
      let res = await EmployeesApi.getFiledList()
      // console.log('获取修改字段下拉框 res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.fieldNameOps = res.data.data.map(item => {
          return { label: item, value: item }
        })
      }
    },

    radioChange(event) {
      // console.log('event: ', event)
    },

    // 批量修改-上传前文件
    handleBeforeUploadBatchModify (file) {
      this.errorData.isError = false
      this.file = file
      console.log('file: ', this.file)
      return false
    },

    // 上传成功
    uploadSuccessBatchModify (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.code === 200 && res.success) {
        if (res.data) {
          this.$Message.error({
            content: res.message,
            duration: 10,
            closable: true
          })
          this.errorData.isError = true
          this.errorData.downLoadUrl = baseUrl + res.data
          this.isCanSubmit = true
        } else {
          this.$Message.success(res.message)
          this.isShowBatchModifyModal = false
          this.errorData.isError = false
          this.file = null
          this.$emit('query')
        }
      } else {
        this.isCanSubmit = true
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 确定导入
    handleSubmitBatchModify () {
      this.isCanSubmit = false
      if (this.formData.importType == 1 && !this.formData.fieldName) {
        this.isCanSubmit = true
        this.$Message.warning('请选择修改字段！')
      } else if (!this.file) {
        this.isCanSubmit = true
        this.$Message.warning('请选择文件！')
      } else {
        this.$refs.upload.post(this.file)
      }
    },

    handleMaxSizeTen () {
      this.$emit('handleMaxSizeTen')
    }
  }
}
</script>

<style lang="less" scope>
</style>
